//index.js
const app = getApp()
const host = app.globalData.host;
Page({
  data: {
    avatarUrl: '',
    nickName: '',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    projectList: [],
    scrollHeight: 0,
    mainProjectDict: {
      creatorNickName: "",
      createTimeStamp: 0,
      creatorOpenid: "",
      mainProject: true,
      projectId: "",
      projectName: "",
      projectStatus: "",
      workersCount: 0
    },
    currPage: 0,
    queryingProjects: false,
  },
  onShow: function(){
    var that = this;
    /*
    if(that.data.projectList.length >= 1){
      this.setData({
        projectList: that.data.projectList,
      });
    }*/
    wx.request({
      url: host + 'city360/project/getMainProject',
      complete: res => {
        console.log("主要项目信息", res);
        var data = res.data;
        //下载主要项目图片
        wx.request({
          url: host + 'city360/project/queryCandidateScheme',
          method: "POST",
          data: {
            projectId: data.projectId
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          complete: res=>{
            console.log(res.data.imageFileName);
            if(res.data.imageFileName){
              data.imgSrc = host + res.data.imageFileName;
            }
            that.setData({
              mainProjectDict: data
            })
            
          }
        });
        
      }
    })

    //查询近期的十个数据
    /*
    wx.request({
      url: host + 'city360/project/query_batch_projects',
      method: "POST",
      data: {
        order_by: "createTimeStamp",
        start: 0,
        end: 10,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      complete: res => {
        console.log("查询第一页， 按照时间", res);
        if (res.statusCode === 200) {
          var data = res.data;
          //下载他们的照片
          //var downloadTasks = []
          for (let i = 0; i < data.length; i++) {
            //downloadTasks.push(do_download_img(that, data[i].imageFileName));
            data[i].imgSrc = host + data[i].imageFileName + ".jpg";
          }
          //Promise.all(downloadTasks).then(results=>{
          that.setData({
            projectList: data,
            queryingProjects: false,
          });
          wx.stopPullDownRefresh();
          //})
        }

      }
    })*/
  },

  onLoad: function() {
    var that = this;
    that.setData({
      currPage: 0,
      queryingProjects: true,
    })
    wx.getSystemInfo({
      success: function(res) {
        console.log(res);
        // 可使用窗口宽度、高度
        console.log('height=' + res.windowHeight);
        console.log('width=' + res.windowWidth);
        // 计算主体部分高度,单位为px
        that.setData({
          // second部分高度 = 利用窗口可使用高度 - first部分高度（这里的高度单位为px，所有利用比例将300rpx转换为px）
          scrollHeight: res.windowHeight - res.windowWidth / 750 * 650
        })
      }
    })

    this.setData({
      userInfo: app.globalData.userInfo,
      avatarUrl: app.globalData.userInfo.avatarUrl,
      nickName: app.globalData.userInfo.nickName
    });

    //从服务器上下载mainProject的信息
    //和展示的project的信息
    /*
    wx.request({
      url: 'https://www.city-tech360.com/city360/project/getMainProject',
      complete: res => {
        console.log("主要项目信息", res);
        var data = res.data;
        //下载主要项目图片
        data.imgSrc = host + data.imageFileName + ".jpg";
        //do_download_img(that, data.imageFileName);
        //data.imgSrc = get_img_path(data.imageFileName);
        that.setData({
          mainProjectDict: data
        })
        //downloadTask.onProgressUpdate((res) => {
        //  console.log('下载进度', res.progress)
        //  console.log('已经下载的数据长度', res.totalBytesWritten)
        //  console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
        //})
        //
      }
    })

    //查询近期的十个数据
    wx.request({
      url: 'https://www.city-tech360.com/city360/project/query_batch_projects',
      method: "POST",
      data:{
        order_by:"createTimeStamp",
        start:0,
        end:10,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      complete: res=>{
        console.log("查询第一页， 按照时间", res);
        if(res.statusCode === 200){
          var data = res.data;
          //下载他们的照片
          //var downloadTasks = []
          for(let i = 0; i < data.length; i++){
            //downloadTasks.push(do_download_img(that, data[i].imageFileName));
            data[i].imgSrc = host + data[i].imageFileName + ".jpg";
          }
          //Promise.all(downloadTasks).then(results=>{
            that.setData({
              projectList: data,
              queryingProjects: false,
            });
          wx.stopPullDownRefresh();
          //})
        }

      }
    })*/

  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function() {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]

        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

  avatarTapped: function(e) {
    console.log("点击了头像");
    wx.navigateTo({
      url: '../personalCenter/personalCenter',
    })
  },
  scrollToBottom: function(e) {
    console.log("滑动到了底部");
    var that = this;
    //查询时间更靠后的十个项目
    if(this.data.projectList.length === 10 * (this.data.currPage + 1)){
      //项目数量小于页面的最大盛放项目数量时，不加载
      if(this.data.queryingProjects === false){
        //当上一次查询未完成时，不加载
        console.log("符合查询条件，开始查询");
        this.setData({
          queryingProjects: true,
          currPage: this.data.currPage + 1
        });
        var page = this.data.currPage;
        wx.request({
          url: host + 'city360/project/query_batch_projects',
          method: "POST",
          data: {
            order_by: "createTimeStamp",
            start: 10 * page,
            end: 10 * page + 10,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          complete: res => {
            console.log("查询第" + page.toString() + "页， 按照时间", res);
            if (res.statusCode === 200) {
              var data = res.data;
              //下载他们的照片
              //var downloadTasks = []
              for (let i = 0; i < data.length; i++) {
              //  downloadTasks.push(do_download_img(that, data[i].imageFileName));
                data[i].imgSrc = host + data[i].imageFileName + ".jpg";
              }
              //Promise.all(downloadTasks).then(results => {
              that.setData({
                  projectList: this.data.projectList.concat(data),
                  queryingProjects: false,
                });
              
            }

          }
        })
      }else{
        console.log("上一次查询仍未完成，不进行查询");
      }
    }else{
      console.log("页面未满，不进行查询");
    }


  },

  newProject: function(e) {
    console.log("新建项目")
    wx.redirectTo({
      url: '../newProject/newProject',
    })
  },

  joinProject: function(e) {
    console.log("加入项目")
    wx.navigateTo({
      url: '../joinProject/joinProject',
    })
  },

  tapShareMainProject: function(e) {
    console.log("主要项目分享");
  },

  tapShareNormalProject: function(e) {
    console.log("普通项目分享")
  },

  checkProject: function(e) {
    console.log("查看项目");
    console.log(e);
    var projectId = e.currentTarget.dataset.projectid;
    console.log("项目的id为", projectId);
    wx.navigateTo({
      url: '../projectDesription/projectDescription?projectId=' + projectId,
    })
  },

  onPullDownRefresh: function(){
    this.onLoad();
  },

  myProject: function(){
    wx.navigateTo({
      url: '../myProjects/myProjects',
    })
  }
})


function do_download_img(page, imageFileName) {
  var downloadTask = wx.downloadFile({
    url: host + "city360/downloadImg/" + imageFileName,
    filePath: wx.env.USER_DATA_PATH + '/' + imageFileName + '.jpg',
  });
  return downloadTask;
}

function get_img_path(imageFileName) {
  return wx.env.USER_DATA_PATH + '/' + imageFileName + '.jpg';
}